package com.mrdeer.iot.handler;

import com.mrdeer.common.tools.JsonUtils;
import com.mrdeer.iot.bean.ChannelInfo;
import com.mrdeer.iot.bean.command.Instruction;
import com.mrdeer.iot.bean.command.InstructionBuilder;
import com.mrdeer.iot.constant.FrameConst;
import com.mrdeer.iot.rabbitmq.MQDeviceEventSender;
import com.mrdeer.iot.utils.HexHelper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 消息队列
 *
 * @Author: xie jianchu
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class MQDeviceEventHandler extends ChannelInboundHandlerAdapter {

    public MQDeviceEventHandler() {
    }

    @Resource
    private MQDeviceEventSender mqSender;

    private static MQDeviceEventHandler mqHandler;

    @PostConstruct
    public void init() {
        mqHandler = this;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ChannelInfo)) {
            return;
        }
        //到这里的都是控制指令
        ChannelInfo channelInfo = (ChannelInfo) msg;
        String command = InstructionBuilder.buildInstruction(channelInfo.getProtocol(), HexHelper.numToHex16(Instruction.ControlFrame.complete_machine.search), FrameConst.control);
        log.info("sn:{} send ... {}", channelInfo.getProtocol().getDest(), command);
        channelInfo.setCommand(command);
        String dataStr = JsonUtils.str2Json(channelInfo);
        log.info("dest:{},dataStr: {}", channelInfo.getProtocol().getDest(), dataStr);
        mqHandler.mqSender.send(channelInfo.getEmqExchanges(), dataStr);
    }
}
